package spe.ui.editor.part;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.editparts.AbstractTreeEditPart;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IActionFilter;

import spe.Activator;
import spe.model.spem.MethodPlugin;
import spe.model.spem.NodeElement;
import spe.model.spem.SPEMElement;

public abstract class OutlineEditPart extends AbstractTreeEditPart implements
PropertyChangeListener, IActionFilter
{
	
	public OutlineEditPart(SPEMElement model) {
		setModel(model);
	}
	
	protected Image getImage() 
	{
		SPEMElement model = (SPEMElement) getModel();
		if(model instanceof NodeElement)
			return ((NodeElement)model).getIconDescriptor().createImage();
		return null;
	}

	protected String getText() {
		String result = ((SPEMElement)getModel()).getName();
		return result == null ? super.getText() : ((SPEMElement)getModel()).getElementId();
	}
	
	private SPEMElement getSPEElement() {
		return (SPEMElement)getModel();
	}

	@Override
	public void activate() {
		if (!isActive()) 
		{
			//System.out.println(String.format("[OutlineEditPart] activated %s", getModel()));
			getSPEElement().addPropertyChangeListener(this);
			super.activate();
		}
	}
	
	@Override
	public void deactivate() {
		if (isActive()) {
			getSPEElement().removePropertyChangeListener(this);
			super.deactivate();
		}
	}		

	protected void handleChildAdd(Object newValue) 
	{
		refreshChildren();
		List children = getChildren();
		for (int i = 0; i < children.size(); i++) 
		{
			EditPart part = (EditPart)children.get(i);
			if (part.getModel() == newValue) {
				part.getViewer().select(part);
			}
		}
	}
	
	public void propertyChange(PropertyChangeEvent evt) 
	{
		String eventName = evt.getPropertyName();
		//if (eventName.equals("name")) {
			refreshVisuals();
		//}
		//this.getText();
	}

	public boolean testAttribute(Object target, String name, String value) {
		return false;
	}
		
}
